package ar.uade.distribuidas.tpo.srv.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import ar.uade.distribuidas.tpo.base.dominiodto.OrdenDeCompraDTO;
import ar.uade.distribuidas.tpo.base.dominiodto.OrdenDePedidoDTO;
import ar.uade.distribuidas.tpo.srv.dao.OrdenDeCompraSaverXMLDAO;
import ar.uade.distribuidas.tpo.srv.dao.OrdenDeCompraXmlDAO;
import ar.uade.distribuidas.tpo.srv.delegado.BD;


/**
 * Servlet implementation class OrdenCompra
 */
@WebServlet("/OrdenCompra")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10,      // 10MB
maxRequestSize=1024*1024*50)   // 50MB
public class OrdenCompra extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrdenCompra() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/ordencompra.jsp");
		   
	  	
		Long cuil = Long.valueOf(request.getParameter("cuil"));
		Part parteArch = request.getPart("file");
		 InputStream filecontent = parteArch.getInputStream();
	
		 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			Document doc;
			try {
			builder = factory.newDocumentBuilder();
			doc = builder.parse(filecontent);
			OrdenDeCompraSaverXMLDAO ocDAO = OrdenDeCompraSaverXMLDAO.getInstancia();
			OrdenDeCompraDTO oc = ocDAO.mapStock(doc);
			
			BD.getInstance().altaOC(oc);
			
			
		request.setAttribute("allok", "La solicitud fue procesada correctamente.");
		
		 request.getRequestDispatcher("/jsp/ordencompra.jsp").forward(request, response);
		
		} catch (Exception e) {
			
			request.setAttribute("allerror", "Hubo un error al procesar la solicitud.");
			request.getRequestDispatcher("/jsp/ordencompra.jsp").forward(request, response);
			
			
			
		} 
	}

}
